package it.polito.connectedcar.util;

import java.awt.geom.Point2D;

/**
 * 
 * @author Nicola Aresta
 * 
 */
public class ConnectedCarUtil {

    /**
     * Util method used to find , if any , the intersection between 2 rays in a
     * Cartesian plane. It uses the Cramer method to determine if 2 rays
     * intersect each other.
     * 
     * 
     * @param x1
     *            first ray start point X coordinate
     * @param y1
     *            first ray start point Y coordinate
     * @param x2
     *            first ray end point X coordinate
     * @param y2
     *            first ray end point Y coordinate
     * @param x3
     *            second ray start point X coordinate
     * @param y3
     *            second ray start point Y coordinate
     * @param x4
     *            second ray end point X coordinate
     * @param y4
     *            second ray end point Y coordinate
     * @return the intersection point if the 2 rays intersect , <b>null</b>
     *         otherwise
     */
    public static Point2D raysIntersection(double x1, double y1, double x2,
	    double y2, double x3, double y3, double x4, double y4) {

	double det = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
	if (det == 0.0) { // Lines are parallel.
	    return null;
	}
	double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / det;
	double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / det;

	/*
	 * since we are considering rays and not straight lines , the following
	 * coefficients must be both positive
	 */
	if (ua >= 0.0f && ub >= 0.0f) {
	    // Get the intersection point.
	    return new Point2D.Double((x1 + ua * (x2 - x1)), (y1 + ua * (y2 - y1)));
	}
	/* the 2 rays do not intersect each other */
	return null;
    }
}
